const resJson = require('../../utils/resJson');
const loginModel = require('../../model/login');
const tokenUtils = require('../../utils/token');
const registerModel = require('../../model/register');
const verifyModel = require('../../model/verifyRegister');
const getFriendsModel = require('../../model/Friend/getFriends');
const addFriendRequestModel = require('../../model/Friend/addFriendRequest');
const utils = require('../../utils/index');
const md5 = require("md5");

const User = {
    login: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const {name, password} = req.body;
        await loginModel({name, password: md5(password)})
            .then(data => {
                if (data.length) {
                    const tokenData = {
                        name: data[0].user_name,
                        password: data[0].password,
                        phone: data[0].phone,
                        user_uid: data[0].user_uid
                    };
                    res.end(resJson.returnSuccess({token: tokenUtils.getToken(tokenData)}));
                } else {
                    res.end(resJson.returnError(500, '用户名或密码错误'));
                }
            }).catch(e => {
                res.end(resJson.returnError(500, '用户名或密码错误'));
            })
    },
    register: async (req, res) => {
        let flag = true;
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const {name, password, phone} = req.body;
        // 验证用户名是否存在
        await verifyModel('user_name', name).then(data => {
            if (data.length) {
                res.end(resJson.returnError(500, '用户名已存在'));
                flag = false;
            }
        }).catch(e => {
            res.end(resJson.returnError(500, e));
            flag = false;
        });
        if (!flag) return;
        // 验证手机号是否存在
        await verifyModel('phone', phone).then(data => {
            if (data.length) {
                res.end(resJson.returnError(500, '手机号已存在'));
                flag = false;
            }
        }).catch(e => {
            res.end(resJson.returnError(500, e));
            flag = false;
        });
        if (!flag) return;

        await registerModel(req.body).then(data => {
            res.end(resJson.returnSuccess('注册成功'));
        }).catch(e => {
            res.end(resJson.returnError(500, e));
            flag = false;
        });
        if (!flag) return;
    },
    // Friends Model
    getFriends: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const uid = req.query.id;
        await getFriendsModel(uid).then(async data => {
            if (!data.length) {
                res.end(resJson.returnError(500, '找不到用户'));
            }
            const list = JSON.parse(data[0].friends_list);
            let f_list = [];
            if (list.length) {
                for (let item of list) {
                    let f = await searchFriends('user_uid', item);
                    f_list.push(f[0]);
                }
            }
            res.end(resJson.returnSuccess(f_list));
        })
    },
    getRequest: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const uid = req.query.id;
        await getFriendsModel(uid).then(async data => {
            if (!data.length) {
                res.end(resJson.returnError(500, '找不到用户'));
            }
            const list = JSON.parse(data[0].friend_request);
            let r_list = [];
            if (list.length) {
                for (let item of list) {
                    let f = await searchFriends('user_uid', item);
                    r_list.push(f[0]);
                }
            }
            res.end(resJson.returnSuccess(r_list));
        })
    },
    searchFriends: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const searchKey = req.query.key;
        let data = await searchFriends('user_name', searchKey);
        if (!data.length) {
            data = await searchFriends('phone', searchKey);
        }

        if (data.length) {
            res.end(resJson.returnSuccess(data));
        } else {
            res.end(resJson.returnError(500, '未找到用户'))
        }
    },
    searchFriendById: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const searchKey = req.query.id;
        let data = await searchFriends('user_uid', searchKey);

        if (data.length) {
            res.end(resJson.returnSuccess(data));
        } else {
            res.end(resJson.returnError(500, '未找到用户'))
        }
    },
    addFriend: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const {id} = req.body;
        const token = utils.getCookie(req.headers.cookie, 'token');
        if (!token || token === 'undefined') {
            res.end(JSON.stringify(resJson.returnError(500, '用户未登录')));
            return;
        }
        const data = tokenUtils.verifyToken(token);
        const uid = data.data.user_uid;
        const userInfo = await getFriendsModel(uid);
        const targetUser = await getFriendsModel(id);
        const friendsList = JSON.parse(userInfo[0].friends_list);

        // 判断是否已经是好友
        if (friendsList.includes(id)) {
            res.end(resJson.returnError(500, '你们已经是好友了！'));
            return;
        }

        const request = JSON.parse(targetUser[0].friend_request) || [];
        if (request.includes(uid)) {
            res.end(resJson.returnError(500, '已发送过好友申请，无需重复发送！'));
            return;
        }
        request.push(uid);
        await addFriendRequestModel(id, 'friend_request', request).then(() => {
            res.end(resJson.returnSuccess({}));
        })
    },
    applyFriend: async (req, res) => {
        res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
        const {id} = req.body;
        const token = utils.getCookie(req.headers.cookie, 'token');
        if (!token || token === 'undefined') {
            res.end(JSON.stringify(resJson.returnError(500, '用户未登录')));
            return;
        }
        const data = tokenUtils.verifyToken(token);
        const uid = data.data.user_uid;
        const userInfo = await getFriendsModel(uid);
        const targetUser = await getFriendsModel(id);
        const friendsList = JSON.parse(userInfo[0].friends_list);
        const targetFriendList = JSON.parse(targetUser[0].friends_list);

        // 删除申请列表对应id
        let request = JSON.parse(userInfo[0].friend_request);
        request.splice(request.indexOf(id), 1);
        await addFriendRequestModel(uid, 'friend_request', request);
        // id添加到好友列表
        friendsList.push(id);
        await addFriendRequestModel(uid, 'friends_list', friendsList);
        targetFriendList.push(uid);
        await addFriendRequestModel(id, 'friends_list', targetFriendList);
        res.end(resJson.returnSuccess({}));
    }
};

async function searchFriends(key, value) {
    let data = await verifyModel(key, value);
    if (data.length) {
        data = data.map(item => {
            return {
                "user_uid": item.user_uid,
                "user_name": item.user_name,
                "nickname": item.nickname,
                "sex": item.sex,
                "portrait": item.portrait
            }
        })
    }
    return data;
}


module.exports = User;
